#pragma once

#include <string>
#include "Util.hpp"
#include <sstream>
const std::string sep = "\r\n";
const std::string defaultPath = "./wwwroot"; /*"根目录"从这开始*/
const std::string homePage = "index.html";
const std::string page404 = "./wwwroot/404.html";

class httpRequest
{
public:
    void parse()
    {
        /*获取请求行*/
        std::string line = Util::getRequestLine(inbuffer, sep);
        std::stringstream in(line);
        in >> method >> url >> version;

        auto pos = url.find("?");
        if (pos == std::string::npos)
        {
            /*分析路径*/
            path = defaultPath;
            path += url;
            if (path[path.size() - 1] == '/')
                path += homePage;
        }
        else
        {
            std::string tmpPath = url.substr(0, pos);
            path = defaultPath;
            path += tmpPath;
            if (path[path.size() - 1] == '/')
                path += homePage;
        }

        /*分析后缀*/
        pos = path.rfind(".");
        if (pos == std::string::npos)
            suffix = ".html"; /*默认给网页文件*/
        else
            suffix = path.substr(pos);

        /*分析请求资源的大小*/
        struct stat st;
        stat(path.c_str(), &st);
        size = st.st_size;
    }
    std::string inbuffer;

    /*请求行的每一项*/
    std::string method;
    std::string url; /*url就是客户端要访问服务端资源的路径*/
    std::string version;
    std::string path; /*确定客户端的资源请求路径，方便服务器处理*/

    std::string suffix; /*根据请求资源的后缀确定响应资源类型*/
    int size;           /*请求资源的大小*/
};

class httpResponse
{
public:
    std::string outbuffer;
};